<template>
    <div class="approval-container">
        <!-- 搜索条件区域 -->
        <div class="search-wrapper">
            <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form">
                <!-- 第一行搜索条件 -->
                <div>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="审批编号" prop="approvalNum">
                                <el-input style="height: 30px !important;" v-model="searchForm.approvalNum"
                                    placeholder="审批编号" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" style="text-align: center;">
                            <el-form-item label="审批标题" prop="content">
                                <!-- <el-input v-model="searchForm.content" placeholder="审批内容" clearable></el-input> -->
                                <el-select v-model="searchForm.type" placeholder="请选择" clearable >
                                    <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" style="text-align: center;">
                            <el-form-item label="申请人" prop="userName">
                                <el-input v-model="searchForm.userName" placeholder="申请人" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" style="text-align: right;">
                            <el-form-item label="联系方式" prop="phonenumber">
                                <el-input v-model="searchForm.phonenumber" placeholder="联系方式" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <!-- 第二行搜索条件 -->
                <div>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="申请时间" prop="createTime">
                                <!-- <el-date-picker v-model="searchForm.createTime" type="daterange"
                                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                                    value-format="yyyy-MM-dd"></el-date-picker> -->
                                    <el-date-picker v-model="searchForm.createTime" type="date" value-format="yyyy-MM-dd"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="6" style="text-align: center;">
                            <el-form-item label="创建日期" prop="createTime">
                                    <el-date-picker v-model="searchForm.createTime" type="date" value-format="yyyy-MM-dd"></el-date-picker>
                            </el-form-item>
                        </el-col> -->
                        <el-col :span="18" style="text-align: right;">
                            <div class="search-actions">
                                <el-button style="background-color: #4C6EE2;color: white;" size="small" @click="handleSearch">搜索</el-button>
                                <el-button size="small" @click="resetSearch">重置</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
        </div>

        <!-- 审批状态筛选 -->
        <div class="status-filter" style="display: flex;justify-content: space-between;">
            <el-radio-group v-model="radio" style="margin-top: 5px;" @change="handleStatusChange">
                <el-radio :label="1">全部</el-radio>
                <el-radio :label="2">已审批</el-radio>
                <el-radio :label="3">未审批</el-radio>
            </el-radio-group>
            <div>
                <el-button v-if="configIstrue == 0" @click="editChange(1)" style="background-color: rgb(243, 245, 255);border: 1px solid #4C6EE2;color: #4C6EE2;" size="small" plain>开启修改
                    <el-popover
                        placement="bottom"
                        width="200"
                        trigger="hover"
                        content="启用当周每日9点之后修改订单"
                        popper-class="custom-popover">
                    <i class="el-icon-question el-icon--right" slot="reference" style="margin-left: 0;"></i>
                </el-popover>
                </el-button>
                <el-button v-if="configIstrue == 1" style="background-color: #4C6EE2;color: white;" size="small" plain @click="editChange(0)">已开启修改
                    <el-popover
                        placement="bottom"
                        width="200"
                        trigger="hover"
                        content="启用当周每日9点之后修改订单"
                        popper-class="custom-popover">
                    <i class="el-icon-question el-icon--right" slot="reference" style="margin-left: 0;"></i>
                </el-popover>
                </el-button>
                <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出</el-button>
                <el-button type="danger" size="small" plain icon="el-icon-delete-solid" @click="handleDelete">删除</el-button>
            </div>
        </div>

        <!-- 审批数据表格 -->
        <div class="table-wrapper">
            <el-table 
                :data="tableData" 
                style="width: 100%" 
                v-loading="loading"
                :header-cell-style="{ background: '#f8f8f9' }"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50" align="center"></el-table-column>
                <el-table-column prop="approvalNum" label="审批编号" ></el-table-column>
                <el-table-column prop="code" label="编号" ></el-table-column>
                <el-table-column prop="type" label="审批标题" width="100">
                    <template slot-scope="scope">
                      <div v-if="scope.row.type == 1">
                        套餐审批
                      </div>
                      <div v-if="scope.row.type == 2">
                        员工订餐审批
                      </div>
                    </template>
                </el-table-column>
                <el-table-column prop="userName" label="申请人" width="100" align="left"></el-table-column>
                <el-table-column prop="createTime" label="申请时间" width="100" align="left"></el-table-column>
                <el-table-column prop="content" label="审批内容" width="350">
                    <template slot-scope="scope">
                       
                        <div>
                            <!-- {{ formatContent(scope.row.content).images" }} -->
                            <div v-html="formatContent(scope.row.content)">
                           
                               </div>
                            <div v-if="scope.row.foodCombo && scope.row.foodCombo.coverImage" class="image-container">
                                <img 
                                v-for="(img, index) in JSON.parse(scope.row.foodCombo.coverImage)" 
                                :key="index"
                                :src="img.url" 
                                class="content-image"
                                />
                            </div>
                            </div>
                        </template>
                </el-table-column>
                <el-table-column prop="phonenumber" label="联系方式"  align="left"></el-table-column>
                <el-table-column prop="approvalTime" label="审批时间" align="left"></el-table-column>
                <el-table-column prop="status" label="状态" align="center">
                    <template slot-scope="scope">
                        <el-tag style="background-color: rgb(237, 240, 252);color: #4C6EE2;" v-if="scope.row.status == '1'">
                            待审批
                        </el-tag>
                        <el-tag type="success" v-if="scope.row.status == '2'">
                            通过
                        </el-tag>
                        <el-tag style="background-color: rgb(254, 238, 238);color: red;border: none;" v-if="scope.row.status == '3'">
                            拒绝
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" style="color: #4C6EE2;" @click="handleApprove(scope.row)" v-if="scope.row.status == '1'">同意</el-button>
                        <el-button type="text" size="small" style="color: #4C6EE2;" @click="handleReject(scope.row)" v-if="scope.row.status == '1'">拒绝</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <!-- <el-pagination 
                    @size-change="handleSizeChange" 
                    @current-change="handleCurrentChange"
                    :current-page="pagination.currentPage" 
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pagination.pageSize" 
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total">
                </el-pagination> -->

                <pagination v-show="pagination.total > 0" :total="pagination.total" :page.sync="pagination.currentPage" :limit.sync="pagination.pageSize" @pagination="fetchData" />

            </div>
        </div>
    </div>
</template>

<script>
import { getList, deleteApproval, submitApproval,changerovall,chanconfigl,chanconfigKeyigl } from '@/api/urgency'

export default {
    name: "urgency",
    data() {
        return {
            configIstrue:0,
            searchForm: {
                code: '',
                content: '',
                userName: '',
                approvalName: '',
                createTime: "",
                approvalTime: ""
            },
           
            options: [
                {
                    value: 1,
                    label:"套餐审批"
                },
                {
                    value: 2,
                    label:"员工订餐审批"
                }   
            ],
            radio: 1,
            loading: false,
            tableData: [],
            multipleSelection: [],
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            },
            configName:""
        }
    },
    methods: {
        async editChange(val) {
            const res = await chanconfigl({
                "configId": 101, 
                configKey: "nine.clock.approval",
                configValue: val,
                configName:this.configName
            })
          this.comfigCange()
        },
        async comfigCange() {
            const res = await chanconfigKeyigl("nine.clock.approval")
            console.log(res.msg)
            this.configIstrue = res.data.configValue
            this.configName = res.data.configName
        },
            formatContent(content) {
                const trimmed = content.split('图片:')[0];

// 把 /n 替换成 HTML 换行
return trimmed.replace(/\/n/g, '；<br/>');
  },
        // 表格选择变化
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        
        // 搜索审批列表
        handleSearch() {
            this.pagination.currentPage = 1
            this.fetchData()
        },
        
        // 重置搜索条件
        resetSearch() {
            this.$refs.searchForm.resetFields()
            this.radio = 1
            this.handleSearch()
        },
        
        // 状态筛选变化
        handleStatusChange() {
            this.handleSearch()
        },
        
        // 获取审批列表数据
        fetchData() {
            this.loading = true
            const params = {
                pageNum: this.pagination.currentPage,
                pageSize: this.pagination.pageSize,
                code: this.searchForm.code,
                content: this.searchForm.content,
                userName: this.searchForm.userName,
                type: this.searchForm.type || null,
                approvalName: this.searchForm.approvalName,
                createTime: this.searchForm.createTime || null,
                phonenumber:this.searchForm.phonenumber || null,
                approvalNum:this.searchForm.approvalNum || null,
                status: this.radio === 1 ? '' : this.radio === 2 ? '2,3' : '1'
            }
            
            // 添加时间范围查询
            if (this.searchForm.createTime && this.searchForm.createTime.length === 2) {
                params.createTimeStart = this.searchForm.createTime[0]
                params.createTimeEnd = this.searchForm.createTime[1]
            }
            
            if (this.searchForm.approvalTime && this.searchForm.approvalTime.length === 2) {
                params.approvalTimeStart = this.searchForm.approvalTime[0]
                params.approvalTimeEnd = this.searchForm.approvalTime[1]
            }

            if (this.$store.state.user.roles.filter(el => el == 'canteen_admin').length > 0) {
                params.type = 2;
            }
            
            getList(params).then(response => {
                this.tableData = response.rows || []
                this.pagination.total = response.total || 0
            }).catch(error => {
                console.error('获取审批列表失败:', error)
            }).finally(() => {
                this.loading = false
            })
        },
        
        // 分页大小改变
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.fetchData()
        },
        
        // 当前页改变
        handleCurrentChange(val) {
            this.pagination.currentPage = val
            this.fetchData()
        },
        
        // 同意审批
        handleApprove(row) {
            this.$confirm('确定要同意该审批吗?', '提示', {
                type: 'warning'
            }).then(() => {
                if (row.type == 1) {
                    return submitApproval({
                    id: row.id,
                    type: row.type,
                    code:row.code,
                    status: '2' // 0表示同意
                })
                } else {
                    return changerovall({
                        changeOrderId: row.changeOrderId,
                        id: row.id,
                        orderType:row.orderType,
                    code:row.code,
                    status: '2' // 0表示同意
                })
                }
               
            }).then(() => {
                this.$message.success('审批已同意')
                this.fetchData()
            })
        },
        
        // 拒绝审批
        handleReject(row) {
            this.$confirm('确定要拒绝该审批吗?', '提示', {
                type: 'warning'
            }).then(() => {
                if (row.type == 1) {
                    return submitApproval({
                    id: row.id,
                    type: row.type,
                    code:row.code,
                    status: '3' // 1表示拒绝
                })
                } else {
                    return changerovall({
                        changeOrderId: row.changeOrderId,
                        code:row.code,
                        id: row.id,
                        orderType:row.orderType,
                      status: '3' // 1表示拒绝
                })
                }
                
            }).then(() => {
                this.$message.success('审批已拒绝')
                this.fetchData()
            })
        },
        
        // 删除审批记录
        handleDelete() {
            if(this.multipleSelection.length === 0) {
                this.$message.warning('请至少选择一条记录')
                return
            }
            
            this.$confirm('确定要删除选中的审批记录吗?', '提示', {
                type: 'warning'
            }).then(() => {
                const ids = this.multipleSelection.map(item => item.id).join(',')
                return deleteApproval(ids)
            }).then(() => {
                this.$message.success('删除成功')
                this.fetchData()
            })
        },
        
        // 导出数据
        handleExport() {
            // this.$message.info('导出功能待实现')
            this.download('food/approval/export', {
        ...this.searchForm
      }, `审批导出${new Date().toISOString().slice(0, 10)}.xlsx`)
        }
    },
    mounted() {
        this.fetchData()
        this.comfigCange()
    }
}
</script>

<style scoped>
/* 自定义弹框样式 */
.custom-popover {
  background-color: #f0f9eb; /* 背景色 */
  border: 1px solid #67c23a; /* 边框 */
}

/* 标题样式 */
.custom-popover .el-popover__title {
  color: #67c23a; /* 标题颜色 */
  font-size: 14px;
}

/* 内容样式 */
.custom-popover {
  color: #606266; /* 内容文字颜色 */
  line-height: 1.6;
}
.image-container {
  display: flex;
  flex-wrap: wrap;
  margin-top: 8px;
}

.content-image {
  max-width: 100px;
  max-height: 100px;
  margin-right: 8px;
  margin-bottom: 8px;
  border-radius: 4px;
  object-fit: cover;
}
::v-deep .el-radio__input.is-checked .el-radio__inner {
    background-color: #4C6EE2;
    border: 1px solid #4C6EE2;
    color: black;
}
::v-deep .el-radio__input.is-checked + .el-radio__label{
    color: black;
}
::v-deep .el-form-item{
    margin-bottom: 10px;
}
::v-deep .el-input--medium .el-input__inner {
    height: 32px;
    line-height: 32px;
    border-radius: 8px;
    background: rgba(0, 0, 0, 0);
    box-sizing: border-box;
    border: 1px solid rgba(0, 0, 0, 0.2);
}

.approval-container {
    padding: 20px;
    background: #fff;
}

.search-wrapper {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-direction: column;
}

.search-row {
    display: flex;
    margin-bottom: 15px;
}

.search-row .el-form-item {
    margin-right: 20px;
    margin-bottom: 0;
}

.search-actions {
    margin-left: auto;
    padding-right: 10px;
}

.status-filter {
    margin-bottom: 15px;
}

.table-wrapper {
    margin-top: 20px;
}

.content-cell {
    padding: 5px 0;
}

.content-cell p {
    margin: 5px 0;
    line-height: 1.5;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.el-table::before {
    display: none;
}

.el-table {
    border: none;
}

.el-table /deep/ th {
    border-bottom: 1px solid #ebeef5;
}

.el-table /deep/ td {
    border-bottom: 1px solid #ebeef5;
}
</style>